﻿using System;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace DMirrorMySQL
{
    public partial class UI : Form
    {
        public UI()
        {
            InitializeComponent();
            dm = new DMirror(Properties.Settings.Default.MySQL_DB,
                            Properties.Settings.Default.MySQL_User,
                            Properties.Settings.Default.MySQL_Pass,
                            Properties.Settings.Default.MySQL_Server);
            dm.initTagList();
            dm.debugMode = true;

            SConsole.AllocConsole();

            initializeSiteDropdown();
        }

        public DMirror dm;

        private void initializeSiteDropdown()
        {
            dsShow.DropDownItems.Clear();
            DataTable dl = dm.initSites();
            ToolStripMenuItem x;
            foreach (DataRow item in dl.Rows)
            {
                x = new ToolStripMenuItem(item[2].ToString());
                x.ToolTipText = item[1].ToString();
                x.Tag = item[0].ToString();
                x.Click += new EventHandler(dsShowClick);
                dsShow.DropDownItems.Add(x);
            }
        }

        private void btn_import_xml_Click(object sender, EventArgs e)
        {
            ofd.Title = "选择需要导入的XML";
            ofd.Filter = "Danbooru Post XML|*.xml|All|*.*";
            int k = -1;
            int.TryParse((string)dsShow.Tag, out k);
            Console.WriteLine("Ready to Import into Site:" + k.ToString());

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                Console.WriteLine(ofd.FileNames.Length.ToString() + " source files found, importing");
                XMLWorker x;
                foreach (string item in ofd.FileNames)
                {
                    x = new XMLWorker(ref dm, k);
                    Console.WriteLine(String.Format("{0}  Parsing :{1}", DateTime.Now.ToShortTimeString(), Path.GetFileName(item)));
                    Console.WriteLine(String.Format("{0}    {1}", x.ImportXML(item), DateTime.Now.ToShortTimeString()));
                    Console.WriteLine(dm.getSiteStatus(k));
                }
                MessageBox.Show("All Done");
            }
        }

        private void btn_sync_lst_Click(object sender, EventArgs e)
        {
            ofd.Title = "选择需要同步的file.lst";
            ofd.Filter = "ls -l > filename.lst |*.lst";
            ofd.FileName = "*.lst";
            ofd.Multiselect = false;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                ListWorker w = new ListWorker(ref dm, 0);
                w.sync_ls_list(ofd.FileName);
                MessageBox.Show("All Done");
            }
        }

        private void btn_wget_lst_Click(object sender, EventArgs e)
        {
            sfd.Title = "填写需要生成的lst";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                ListWorker w = new ListWorker(ref dm, 0);
                w.get_broken_list(sfd.FileName, 3);
            }
        }

        private void btn_mv_lst_Click(object sender, EventArgs e)
        {
            sfd.Title = "填写需要生成的lst";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                ListWorker w = new ListWorker(ref dm, 0);
                w.get_conflict_list(sfd.FileName);
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
        }

        private void 添加TagToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void toolStripComboBox1_Click(object sender, EventArgs e)
        {
        }

        private void initialPostXMLsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            sfd.Title = "Please select where to put initial post.xml lst";
            sfd.FileName = (string)dsShow.ToolTipText + ".lst";
            sfd.Filter = "All|*.*";
            string re = "";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                for (int i = 2; i < 1000; i++)
                {
                    re += string.Format("\nhttp://{0}/post/index.xml?limit=1000&page={1}", (string)dsShow.ToolTipText, i.ToString());
                }
                File.WriteAllText(sfd.FileName, re, Encoding.UTF8);
                MessageBox.Show("Done");
            }
        }

        private void dsShowClick(object sender, EventArgs e)
        {
            ToolStripMenuItem i = (ToolStripMenuItem)sender;

            foreach (ToolStripMenuItem x in dsShow.DropDownItems)
            {
                x.CheckState = CheckState.Unchecked;
            }

            i.CheckState = CheckState.Checked;
            dsShow.Tag = i.Tag;
            dsShow.Text = "D:" + i.Text;
            dsShow.ToolTipText = i.ToolTipText;
            importPostXML.Text = "Import Post.XML(s) into " + i.Text;
            Console.WriteLine(string.Format("[{0}]{2}={1} Selected", (string)i.Tag, i.ToolTipText, i.Text));
            Console.WriteLine(dm.getSiteStatus((string)i.Tag));
        }

        private void initialPostXMLWgetSHToolStripMenuItem_Click(object sender, EventArgs e)
        {
            sfd.Title = "Please select where to put initial post.xml lst";
            sfd.FileName = (string)dsShow.ToolTipText + ".lst";
            sfd.Filter = "All|*.*";
            string re = "@echo off";
            sfd.FileName = Path.ChangeExtension(sfd.FileName, "sh");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                for (int i = 1; i < 1000; i++)
                {
                    re += string.Format("echo post {1}000 downloading \nsleep 1\nwget -nv --no-cache --random-wait -O {0}_{1}.xml http://{0}/post/index.xml?limit=1000&page={1}\n", (string)dsShow.ToolTipText, i.ToString());
                }
                File.WriteAllText(sfd.FileName, re, Encoding.UTF8);
                MessageBox.Show("Done");
            }
        }

        private void konachanToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ofd.Title = "选择需要导入的XML";
            ofd.Filter = "Danbooru Post XML|*.xml|All|*.*";
            ofd.Multiselect = true;
            int k = -1;
            int.TryParse((string)dsShow.Tag, out k);

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                XMLWorker x = new XMLWorker(ref dm, k);
                foreach (string item in ofd.FileNames)
                {
                    Console.WriteLine("Parsing :" + Path.GetFileName(item));
                    Console.WriteLine(x.ImportXML(item));
                }
                MessageBox.Show("All Done");
            }
        }

        private void konachannotagToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void UI_Load(object sender, EventArgs e)
        {
        }

        private void thumbLSTToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ofd.Title = "Choose thumbnail list to be imported";
            ofd.Filter = "ls -1 > file.lst|*.lst";
            ofd.FileName = "*.lst";
            ofd.Multiselect = true;
            string site_id = (string)dsShow.Tag;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                foreach (string item in ofd.FileNames)
                {
                    LSTWorker.importThumbList(site_id, ref dm, item);
                    Console.WriteLine(dm.getSiteStatus(site_id));
                }
            }
        }

        private void thumbDownlstToolStripMenuItem_Click(object sender, EventArgs e)
        {
            sfd.Title = "Please select where to put thumb down lst";
            sfd.FileName = (string)dsShow.ToolTipText + "_";
            sfd.Filter = "All|*.*";
            string site_id = (string)dsShow.Tag;
            //  string re = "";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                string[] s = dm.getThumbDownList(site_id);
                string[] r = { "", "", "" };
                FileStream f = new FileStream(sfd.FileName + "td.lst", FileMode.Create);
                StreamWriter w = new StreamWriter(f);
                foreach (string item in s)
                {
                    w.WriteLine(item);
                }
                w.Flush();
                w.Dispose();
                f.Dispose();
            }
        }

        private void idMD5shToolStripMenuItem_Click(object sender, EventArgs e)
        {
            sfd.Title = "Please select where to put thumb down lst";
            sfd.FileName = (string)dsShow.ToolTipText + "_";
            sfd.Filter = "All|*.*";
            string site_id = (string)dsShow.Tag;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                DataTable d = new DataTable();
                string kx = "";
                dm.getData(string.Format("select post_id,md5,url from posts_{0}", site_id), ref d);
                int z = d.Rows.Count;
                Console.WriteLine(z.ToString() + " posts select from db");
                FileStream k = new FileStream(sfd.FileName + ".sh", FileMode.Create);
                StreamWriter w = new StreamWriter(k);

                w.Write(string.Format("mkdir ../got{0}\n", site_id));
                foreach (DataRow i in d.Rows)
                {
                    kx = Path.GetExtension(i[2].ToString());
                    w.Write(string.Format("mv {0}{2} ../got{3}/{1}{2}\n", i[0].ToString(), i[1].ToString(), kx, site_id));
                }
                w.Flush();
                w.Dispose();
                //k.Flush();
                k.Dispose();
                d.Dispose();
            }
        }

        private void dirThumbsl3ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string site_id = (string)dsShow.Tag;
            fbd.Description = string.Format("Select where to generate thumb_{0}.sl3", site_id);

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                string dbfn = string.Format("{0}\\thumb_{1}.sl3", fbd.SelectedPath, site_id);
                bool hasdb = File.Exists(dbfn);
                SQLiteConnection s = new SQLiteConnection("Data Source=" + dbfn);

                s.Open();
                if (!hasdb)
                {
                    SQLiteCommand c = s.CreateCommand();
                    c.CommandText = string.Format("CREATE TABLE thumb_{0}(md5 TEXT(17) NOT NULL ON CONFLICT REPLACE,jpg BLOB, PRIMARY KEY(md5))", site_id);
                    c.ExecuteNonQuery();
                    Console.WriteLine("SL3 Created");
                }
                else
                {
                    // s.Open();
                    Console.WriteLine("SL3 connected");
                }

                DataTable d = new DataTable();
                dm.getData(string.Format("select md5 from posts_{0}", site_id), ref d);
                Console.WriteLine(d.Rows.Count.ToString() + " thumbs found");
                string f = "";
                SQLiteCommand inj = s.CreateCommand();
                SQLiteTransaction ta = s.BeginTransaction();
                inj.Transaction = ta;
                int cnt = 0;
                int step = 0;
                fbd.Description = string.Format("Select pool of thumbnails for site {0}", site_id);
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    foreach (DataRow i in d.Rows)
                    {
                        cnt++;

                        f = string.Format("{0}\\{1}.jpg", fbd.SelectedPath, i[0].ToString());
                        if (File.Exists(f))
                        {
                            inj.CommandText = string.Format("insert into thumb_{0} (md5,jpg) values(@md5v,@jpgv)", site_id);
                            inj.Parameters.Clear();
                            inj.Parameters.Add(new SQLiteParameter("@md5v", i[0].ToString()));
                            inj.Parameters.Add(new SQLiteParameter("@jpgv", File.ReadAllBytes(f)));
                            inj.ExecuteNonQuery();

                            // if (cnt > 99) { Console.Write("."); cnt = 0; }
                            Console.WriteLine(cnt.ToString() + " Import : " + i[0].ToString() + ".jpg");
                            step = cnt / 100;
                            if (cnt == (step * 100))
                            {
                                ta.Commit();
                                ta.Dispose();
                                inj.Dispose();

                                inj = s.CreateCommand();

                                ta = s.BeginTransaction();
                                inj.Transaction = ta;
                                Console.WriteLine("Commit " + step.ToString());
                            }
                        }
                    }
                    ta.Commit();
                }
            }
        }
    }
}